#include <iostream>

#include "Item.hpp"
#include "Tile.hpp"
#include "Zone.hpp"

#include "ItemProperties.hpp"

ItemProperty::ItemProperty(Item* owner, EItemType type) : Type(type), Owner(owner)
{
}

ItemProperty::~ItemProperty()
{
}

EItemType ItemProperty::getItemType()
{
	return Type;
}

PropertyBurning::PropertyBurning(Item* owner, unsigned int burnTimer, unsigned int flammability, unsigned int spreads) : ItemProperty(owner, EIT_BURNABLE), Burning(false), DoneBurning(false), DoneBurningCall(false), BurnTimer(burnTimer), BurnTimerNow(burnTimer), Flammability(flammability), Spreads(spreads), SpreadsNow(0) 
{ 
}

bool PropertyBurning::isBurning()
{
	return Burning;
}

bool PropertyBurning::isDoneBurning()
{
	return DoneBurning;
}

int PropertyBurning::getFlammability()
{
	return Flammability;
}

void PropertyBurning::action()
{
	if (Burning)
	{
		//extinguish here
		Burning = false;
	}
	else
	{
		if (!DoneBurning)
			Burning = true;
	}
}

void PropertyBurning::update()
{
	if (Burning)
	{
		if (BurnTimerNow % 2 == 0)
			Owner->setColor(TCODColor::red, TCODColor::black);
		else
			Owner->setColor(TCODColor::orange, TCODColor::black);

		if (BurnTimerNow <= 100 && SpreadsNow < Spreads)
		{	
			Vector2d pos = Vector2d(TCODRandom::getInstance()->getInt(-1, 1), TCODRandom::getInstance()->getInt(-1, 1));
			Tile* tile;
			if (pos != Vector2d(0, 0) && (tile = Owner->getZone()->getTile(Owner->getPosition()+pos)))
			{
				Item* item = tile->getItems().back();
				PropertyBurning* prop = (PropertyBurning*)item->getProperty(EIT_BURNABLE);
				if (item && !prop->isBurning() && !prop->isDoneBurning() && prop->getFlammability() <= BurnTimer-BurnTimerNow)
				{
					++SpreadsNow;
					item->onBurn();
				}
			}
		}

		--BurnTimerNow;

		if (BurnTimerNow == 0)
		{
			Burning = false;
			DoneBurning = true;

			Owner->setColor(TCODColor::grey, TCODColor::black);
			Owner->setSize(EOS_MINISCULE);
			Owner->setShape(',');
			return;
		}
	}
}
